// pages/board/board.js
import {
  hgetStorage,
  hshowToast
} from '../../static/htools.wx'
import {
  hrequestGet,
  huploadFile,
  hrequestPost,
  hrequestPut,
} from '../../static/hunit.wx'
import api from '../../assets/api'
const {
  getDeptExt,
  upLoadImagefile,
  addUpdateBusBasicInfo,
  houseHold,
  getDictDetail,
  getSSQList,
  subHHInfo,
  baseUrl,
  getTransformer,
  subTransformer
} = api
import WxValidate from '../../static/WxValidate'
Page({
  data: {
    curId: '',
    currentTab: 0,
    capacityIndex: 0,
    //企业基本信息
    deptExtInfo: {},
    region: "",
    areaRegion: [0, 0, 0],
    regionList: [],
    regionCode: [],
    curProvince: '',
    curCity: '',
    curArea: '',
    curProvinceLabel: '',
    curCityLabel: '',
    curAreaLabel: '',
    curSelectArea: '',
    oldRegion: [],
    //开户行信息
    fileList: [],
    khhPic: '',
    idCardZ: [],
    idCardZPic: '',
    idCardF: [],
    idCardFPic: '',
    YYZZ: [],
    YYZZPic: '',
    //户号信息
    houseHoldList: [],
    electricType: [],
    typeIndex: 1,
    electricGrade: ['等级1', '等级2', '等级3'],
    gradeIndex: 0,
    rules2: {},
    messages2: {},
    //变压器信息
    transformerList: [],
    rules3: {},
    messages3: {}
  },
  onLoad(options) {
    if (options.id) {
      this.setData({
        curId: options.id
      })
    }
    this.getElecList()
    this.getDYList()
    this.getRegion(0)
    this.getCity(1)
    this.getArea(2)
    this.getDeptExt()
    this.getHouseHold()
    this.getTransformerList()
    this.initValidateBase()
    this.initValidateHouse()
    this.initValidateTransformer()
  },
  showModal(error) {
    wx.showModal({
      content: error.msg,
      showCancel: false,
    })
  },
  //初始化 户号表单校验规则
  initValidateHouse() {
    const rules = this.data.rules2
    const messages = this.data.messages2
    this.WxValidate2 = new WxValidate(rules, messages)
    this.WxValidate2.addMethod('len', (value, param) => {
      return this.WxValidate2.optional(value) || (value.length == 10)
    }, '请输入10位户号编号')
  },
  //查询户号信息
  async getHouseHold() {
    let _dataJson = {
      deptId: hgetStorage('deptId'),
      page: 0,
      size: 99999999
    }
    let _res = await hrequestGet(houseHold, _dataJson);
    // 获取到数据 户号列表
    let houseHoldList = _res.data.content
    houseHoldList.forEach((v, i) => {
      this.data.rules2['householdNumber' + i] = {
        required: true,
        len: true
      };
      this.data.messages2['householdNumber' + i] = {
        required: '请输入户号编号',
        len: '请输入10位户号编号'
      }
    });
    this.initValidateHouse()

    for (let i = 0; i < this.data.electricType.length; i++) {
      for (let j = 0; j < houseHoldList.length; j++) {
        if (houseHoldList[j].electricityType == this.data.electricType[i].value) {
          houseHoldList[j].elecNum = i
        }
      }
    }
    for (let i = 0; i < this.data.electricGrade.length; i++) {
      for (let j = 0; j < houseHoldList.length; j++) {
        if (houseHoldList[j].voltageLevel == this.data.electricGrade[i].value) {
          houseHoldList[j].elecGradeNum = i
        }
      }
    }
    this.setData({
      houseHoldList
    })
  },
  //新增户号
  addUser() {
    let list = this.data.houseHoldList
    let _newObj = [{
      deptId: hgetStorage('deptId'),
      electricityType: '0',
      elecNum: '0',
      householdNumber: '',
      voltageLevel: '0',
      elecGradeNum: '0'
    }]
    let _newList = list.concat(_newObj)
    _newList.forEach((v, i) => {
      this.data.rules2['householdNumber' + i] = {
        required: true,
        len: true
      };
      this.data.messages2['householdNumber' + i] = {
        required: '请输入户号编号',
        len: '请输入10位户号编号'
      }
    });
    this.initValidateHouse()
    this.setData({
      houseHoldList: _newList
    })
  },
  // 表单验证并 提交户号信息
  async formSubmitHouse(e) {
    const params = e.detail.value
    //校验表单
    if (!this.WxValidate2.checkForm(params)) {
      const error = this.WxValidate2.errorList[0]
      this.showModal(error)
      return false
    }
    //return false
    let _data = this.data.houseHoldList
    let _dataJson = []
    _data.forEach(item => {
      _dataJson.push({
        deptId: item.deptId,
        electricityType: this.data.electricType[item.elecNum].value,
        householdNumber: item.householdNumber,
        id: item.id || '',
        voltageLevel: this.data.electricGrade[item.elecGradeNum].value
      })
    })
    let _res = await hrequestPost(subHHInfo, _dataJson)
    if (_res.statusCode === 204) {
      hshowToast('提交成功')
      this.setData({
        currentTab: 2
      })
    } else {
      hshowToast('提交失败')
    }
  },
  //初始化变压器信息校验规则
  initValidateTransformer() {
    const rules = this.data.rules3
    const messages = this.data.messages3
    this.WxValidate3 = new WxValidate(rules, messages)
  },
  //查询变压器信息
  async getTransformerList() {
    let _dataJson = {
      deptId: hgetStorage('deptId'),
      page: 0,
      size: 99999999
    }
    let _res = await hrequestGet(getTransformer, _dataJson);
    let transformerList = _res.data.content
    transformerList.forEach((v, i) => {
      this.data.rules3['transformerNumber' + i] = {
        required: true
      }
      this.data.messages3['transformerNumber' + i] = {
        required: "请输入变压器编号"
      }
      this.data.rules3['transformerName' + i] = {
        required: true
      }
      this.data.messages3['transformerName' + i] = {
        required: "请输入变压器名称"
      }
      this.data.rules3['transformerCapacity' + i] = {
        required: true
      }
      this.data.messages3['transformerCapacity' + i] = {
        required: "请输入变压器容量"
      }
    })
    this.initValidateHouse()
    this.setData({
      transformerList
    })
  },
  //新增变压器
  addTransformer() {
    let list = this.data.transformerList
    let _newObj = [{
      deptId: hgetStorage('deptId'),
      transformerCapacity: "",
      transformerName: "",
      transformerNumber: ""
    }]
    let _newList = list.concat(_newObj)
    _newList.forEach((v, i) => {
      this.data.rules3['transformerNumber' + i] = {
        required: true
      }
      this.data.messages3['transformerNumber' + i] = {
        required: "请输入变压器编号"
      }
      this.data.rules3['transformerName' + i] = {
        required: true
      }
      this.data.messages3['transformerName' + i] = {
        required: "请输入变压器名称"
      }
      this.data.rules3['transformerCapacity' + i] = {
        required: true
      }
      this.data.messages3['transformerCapacity' + i] = {
        required: "请输入变压器容量"
      }
    })
    this.initValidateHouse()
    this.setData({
      transformerList: _newList
    })
  },
  // 表单验证并 提交变压器信息申报
  async formSubmitTransformer(e) {
    const params = e.detail.value
    //校验表单
    if (!this.WxValidate3.checkForm(params)) {
      const error = this.WxValidate3.errorList[0]
      this.showModal(error)
      return false
    }
    let _data = this.data.transformerList
    let _dataJson = []
    _data.forEach(item => {
      _dataJson.push({
        id: item.id || '',
        deptId: item.deptId,
        transformerCapacity: item.transformerCapacity,
        transformerName: item.transformerName,
        transformerNumber: item.transformerNumber
      })
    })
    let _res = await hrequestPost(subTransformer, _dataJson)
    if (_res.statusCode === 204) {
      hshowToast('提交成功')
      this.setData({
        currentTab: 0
      })
    } else {
      hshowToast('提交失败')
    }
  },
  //初始化基础信息表单校验规则
  initValidateBase() {
    const rules = {
      name: {
        required: true
      },
      contacts: {
        required: true
      },
      phone: {
        required: true,
        tel: true
      }
    }
    const messages = {
      name: {
        required: '请输入企业名称'
      },
      contacts: {
        required: '请输入联系人'
      },
      phone: {
        required: '请输入手机号码',
        tel: '请输入11位的手机号码'
      }
    }
    this.WxValidate1 = new WxValidate(rules, messages)
  },
  // 表单验证并 提交基础信息申报
  async formSubmitBase(e) {
    const params = e.detail.value
    //校验表单
    if (!this.WxValidate1.checkForm(params)) {
      const error = this.WxValidate1.errorList[0]
      this.showModal(error)
      return false
    }
    // 基础信息提交
    let _dataJson = {
      adressDetail: '',
      areaCode: !this.data.areaRegion[2] ? this.data.oldRegion[2] : this.data.areaRegion[2],
      businessLicense: this.data.YYZZPic,
      cityCode: !this.data.areaRegion[1] ? this.data.oldRegion[1] : this.data.areaRegion[1],
      contacts: this.data.deptExtInfo.contacts,
      deptArea: '',
      deptExtType:2, //企业类型（1：售电企业 2：用电企业）
      deptId: hgetStorage('deptId'),
      enabled: false,
      id: this.data.curId,
      idCardFront: this.data.idCardZPic,
      idCardReverse: this.data.idCardFPic,
      industry:'', //经营行业
      legalPersonIdNumber:'123',//法人身份证号
      legalPersonName:'123', //法人姓名
      name: this.data.deptExtInfo.name,
      openingBank: this.data.khhPic,
      phone: this.data.deptExtInfo.phone,
      provinceCode: !this.data.areaRegion[0] ? this.data.oldRegion[0] : this.data.areaRegion[0],
      socialCreditCode:'', //统一社会信用代码
      voltageLeavel: ''
    }
    let _res = await hrequestPut(addUpdateBusBasicInfo, _dataJson)
    if (_res.statusCode === 204) {
      hshowToast('提交成功')
      this.setData({
        currentTab: 1
      })
    } else {
      hshowToast('提交失败')
    }
  },
  //获取省市区
  async getRegion(pid) {
    let _dataJson = {
      pid: pid
    }
    let _res = await hrequestGet(getSSQList, _dataJson)
    this.setData({
      'regionList[0]': _res.data
    })
  },
  async getCity(provinceCode) {
    let _dataJson = {
      pid: provinceCode
    }
    let _res = await hrequestGet(getSSQList, _dataJson)
    this.setData({
      'regionList[1]': _res.data
    })
    this.getArea(_res.data[0].areaId)
  },
  async getArea(cityCode) {
    let _dataJson = {
      pid: cityCode
    }
    let _res = await hrequestGet(getSSQList, _dataJson)
    this.setData({
      'regionList[2]': _res.data
    })
  },
  //获取字典详情
  async getElecList() {
    let _dataJson = {
      dictName: 'electricity_type',
      page: 0,
      size: 999999
    }
    let _res = await hrequestGet(getDictDetail, _dataJson)
    this.setData({
      electricType: _res.data.content
    })
  },
  async getDYList() {
    let _dataJson = {
      dictName: 'voltage_level',
      page: 0,
      size: 999999
    }
    let _res = await hrequestGet(getDictDetail, _dataJson)
    this.setData({
      electricGrade: _res.data.content
    })
  },
  async getBYList() {
    let _dataJson = {
      dictName: 'voltage_level',
      page: 0,
      size: 999999
    }
    let _res = await hrequestGet(getDictDetail, _dataJson)
    this.setData({
      electricGrade: _res.data.content
    })
  },
  //双向绑定企业基本信息
  changeBusName(e) {
    this.setData({
      'deptExtInfo.name': e.detail.value
    })
  },
  changePhone(e) {
    this.setData({
      'deptExtInfo.phone': e.detail.value
    })
  },
  changeContacts(e) {
    this.setData({
      'deptExtInfo.contacts': e.detail.value
    })
  },
  //获取企业基本信息
  async getDeptExt() {
    let deptId = hgetStorage('deptId')
    let _res = await hrequestGet(getDeptExt + '?deptId=' + deptId);
    let deptExtInfo = _res.data;
    console.log(deptExtInfo);
    let region = deptExtInfo.deptArea!=null ? deptExtInfo.deptArea.replace(/,/g, ' '):"山西省 太原市 小店区"
    this.setData({
      deptExtInfo,
      region,
      oldRegion: [deptExtInfo.provinceCode, deptExtInfo.cityCode, deptExtInfo.areaCode],
      fileList: deptExtInfo.openingBank !== '' && deptExtInfo.openingBank !== null ? [{
        url: baseUrl + '/file/' + deptExtInfo.openingBank
      }] : '',
      khhPic: deptExtInfo.openingBank !== '' ? deptExtInfo.openingBank : '',
      idCardZ: deptExtInfo.idCardFront !== '' && deptExtInfo.idCardFront !== null ? [{
        url: baseUrl + '/file/' + deptExtInfo.idCardFront
      }] : '',
      idCardZPic: deptExtInfo.idCardFront !== '' ? deptExtInfo.idCardFront : '',
      idCardF: deptExtInfo.idCardReverse !== '' && deptExtInfo.idCardReverse !== null ? [{
        url: baseUrl + '/file/' + deptExtInfo.idCardReverse
      }] : '',
      idCardFPic: deptExtInfo.idCardReverse !== '' ? deptExtInfo.idCardReverse : '',
      YYZZ: deptExtInfo.businessLicense !== '' && deptExtInfo.businessLicense !== null ? [{
        url: baseUrl + '/file/' + deptExtInfo.businessLicense
      }] : '',
      YYZZPic: deptExtInfo.businessLicense !== '' ? deptExtInfo.businessLicense : ''
    })
  },
  //选择开户行
  async afterRead(e) {
    let _file = e.detail.file.path
    let _newFile = []
    _newFile.push({
      url: _file
    })
    this.setData({
      fileList: _newFile
    })
    let _res = await huploadFile(upLoadImagefile, e.detail.file.path, "imagefile")
    this.setData({
      khhPic: _res
    })
  },
  // 删除开户行
  delFiles() {
    this.setData({
      fileList: [],
      khhPic: ''
    })
  },
  //选择法人身份证正面
  async afterIdCardZ(e) {
    let _file = e.detail.file.path
    let _newFile = []
    _newFile.push({
      url: _file
    })
    this.setData({
      idCardZ: _newFile
    })
    let _res = await huploadFile(upLoadImagefile, e.detail.file.path, "imagefile")
    this.setData({
      idCardZPic: _res
    })
  },
  //删除法人身份证正面
  delIdCardZ() {
    this.setData({
      idCardZ: [],
      idCardZPic: ''
    })
  },
  //选择法人身份证反面
  async afterIdCardF(e) {
    let _file = e.detail.file.path
    let _newFile = []
    _newFile.push({
      url: _file
    })
    this.setData({
      idCardF: _newFile
    })
    let _res = await huploadFile(upLoadImagefile, e.detail.file.path, "imagefile")
    this.setData({
      idCardFPic: _res
    })
  },
  //删除法人身份证反面
  delIdCardF() {
    this.setData({
      idCardF: [],
      idCardFPic: ''
    })
  },
  //选择营业执照
  async afterYYZZ(e) {
    let _file = e.detail.file.path
    let _newFile = []
    _newFile.push({
      url: _file
    })
    this.setData({
      YYZZ: _newFile
    })
    let _res = await huploadFile(upLoadImagefile, e.detail.file.path, "imagefile")
    this.setData({
      YYZZPic: _res
    })
  },
  //删除营业执照
  delYYZZ() {
    this.setData({
      YYZZ: [],
      YYZZPic: ''
    })
  },
  //选择地区
  bindRegionArea(e) {
    let _column = e.detail.column
    if (_column == 0) {
      this.setData({
        curProvince: e.detail.value,
      })
      this.setData({
        curProvinceLabel: this.data.regionList[0][this.data.curProvince].name
      })
      this.getCity(this.data.regionList[0][this.data.curProvince].areaId)
      this.setData({
        areaRegion: [this.data.curProvince, 0, 0]
      })
    } else if (_column == 1) {
      this.setData({
        curCity: e.detail.value
      })
      this.setData({
        curCityLabel: this.data.regionList[1][this.data.curCity].name
      })
      this.getArea(this.data.regionList[1][this.data.curCity].areaId)
      this.setData({
        areaRegion: [this.data.curProvince, this.data.curCity, 0]
      })
    } else if (_column == 2) {
      this.setData({
        curArea: e.detail.value,
      })
      this.setData({
        areaRegion: [this.data.curProvince, this.data.curCity, this.data.curArea],
        curAreaLabel: this.data.regionList[2][this.data.curArea].name
      })
    }
  },
  areaSelect(e) {
    let _num = e.detail.value
    let _province = _num[0]
    let _city = _num[1]
    let _area = _num[2]
    if (_num[0] == '') {
      _province = 0
    }
    if (_num[1] == '') {
      _city = 0
    }
    if (_num[2] == '') {
      _area = 0
    }
    this.setData({
      curSelectArea: [this.data.regionList[0][_province].name, this.data.regionList[1][_city].name, this.data.regionList[2][_area].name].join(' '),
      areaRegion: [this.data.regionList[0][_province].areaId, this.data.regionList[1][_city].areaId, this.data.regionList[2][_area].areaId]
    })

  },
  //选择用电类型
  bindPickerType(e) {
    let index = e.target.dataset.index;
    let a = 'houseHoldList[' + index + '].elecNum'
    this.setData({
      [a]: e.detail.value
    })
  },
  //选择电压等级
  bindPickerGrade(e) {
    let index = e.target.dataset.index;
    let a = 'houseHoldList[' + index + '].elecGradeNum'
    this.setData({
      [a]: e.detail.value
    })
  },
  changeHouseNumber(e) {
    let index = e.target.dataset.index;
    let a = 'houseHoldList[' + index + '].householdNumber'
    this.setData({
      [a]: e.detail.value
    })
  },
  //双向 绑定变压器数据
  changeTransformerNumber(e) {
    let index = e.target.dataset.index;
    let a = 'transformerList[' + index + '].transformerNumber'
    this.setData({
      [a]: e.detail.value
    })
  },
  changeTransformerName(e) {
    let index = e.target.dataset.index;
    let a = 'transformerList[' + index + '].transformerName'
    this.setData({
      [a]: e.detail.value
    })
  },
  changeTransformerCapacity(e) {
    let index = e.target.dataset.index;
    let a = 'transformerList[' + index + '].transformerCapacity'
    this.setData({
      [a]: e.detail.value
    })
  },
  //滑动切换
  swiperTab(e) {
    this.setData({
      currentTab: e.detail.current
    });
  },
  //点击切换
  clickTab(e) {
    if (this.data.currentTab === e.target.dataset.current) {
      return false;
    } else {
      this.setData({
        currentTab: e.target.dataset.current
      })
    }
  }
})